package 尚硅谷;

import java.lang.ref.SoftReference;

/**
 * @author zhangmin
 * @create 2022-03-25 22:34
 * 软引用
 */
public class SoftReferenceDemo {
    /*内存够用*/
    public static void softRefMemoryEnough() {
        Object o1=new Object();
        SoftReference<Object> softReference=new SoftReference<>(o1);
        System.out.println(o1);
        System.out.println(softReference);

        o1=null;
        System.gc();
        System.out.println(o1);
        System.out.println(softReference.get());//内存够用时，软引用不会被回收
    }
    /*内存不够用*/
    public static void softRefMemoryNoEnough() {
        Object o1=new Object();
        SoftReference<Object> softReference=new SoftReference<>(o1);
        System.out.println(o1);
        System.out.println(softReference);

        o1=null;

        try {
            byte[] bytes=new byte[1024*1024*1024];//故意申请大对象，使得内存不够
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            System.out.println(o1);
            System.out.println(softReference.get());
        }
    }
    public static void main(String[] args) {
        softRefMemoryEnough();
        System.out.println("======================================================");
        softRefMemoryNoEnough();
    }
}
